package com.chat.app.config.swagger;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class Swagger2Config extends WebMvcConfigurationSupport {


    @Bean
    public Docket docket(SwaggerProperty swaggerProperty) {
        System.out.println("----------------------------");
        return new Docket(DocumentationType.SWAGGER_2). // 文档类型为swagger2
                apiInfo(apiInfo(swaggerProperty)). // api 接口的介绍信息
                select().
                apis(RequestHandlerSelectors.basePackage(swaggerProperty.getBasePackage())). // 我要对那个包生成文档 com.sxt.controller
                build();
    }

    private ApiInfo apiInfo(SwaggerProperty swaggerProperty) {
        Contact contact = new Contact(swaggerProperty.getName(), swaggerProperty.getUrl(), swaggerProperty.getEmail());
        return new ApiInfoBuilder().
                contact(contact).
                version(swaggerProperty.getVersions()).
                title(swaggerProperty.getTitle()).
                description(swaggerProperty.getDescription()).
                termsOfServiceUrl(swaggerProperty.getTermsOfServiceUrl()).
                license(swaggerProperty.getLicense()).build();
    }

    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 解决静态资源无法访问
        registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
        // 解决swagger无法访问
        registry.addResourceHandler("/swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        // 解决swagger的js文件无法访问
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
        super.addResourceHandlers(registry);

    }

}
